<template>
  <el-container class="goods-view panel-block">
    <el-header class="sa-header">
      <el-tabs class="sa-tabs" v-model="filterParams.data.status" @tab-change="getData(1)">
        <el-tab-pane
            v-for="sl in statusList.data"
            :key="sl"
            :label="sl.name"
            :name="sl.type"
        ></el-tab-pane>
      </el-tabs>
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">
          <span class="left">商品列表</span>
          <search-condition
              :conditionLabel="filterParams.conditionLabel"
              @deleteFilter="deleteFilter"
          ></search-condition>
        </div>
        <div>
          <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
          <el-button class="sa-button-refresh" icon="Search" @click="openFilter"></el-button>
          <el-button type="primary" @click="uploadFile" v-auth="'shop.admin.goods.goods.upload'">导入</el-button>
          <el-button
              v-auth="'shop.admin.goods.goods.add'"
              icon="Plus"
              type="primary"
              @click="addRow"
          >新建
          </el-button
          >
          <el-button
              v-auth="'shop.admin.goods.goods.recyclebin'"
              type="danger"
              icon="Delete"
              plain
              @click="openRecyclebin"
          >回收站
          </el-button
          >
        </div>
      </div>
    </el-header>
    <el-main class="sa-p-0">
      <div class="sa-table-wrap" v-loading="loading">
        <el-table
            height="100%"
            class="sa-table"
            :data="table.data"
            @selection-change="changeSelection"
            @sort-change="fieldFilter"
            @row-dblclick="editRow"
            :expand-row-keys="expandRowKeys"
            row-key="id"
            stripe
        >
          <template #empty>
            <sa-empty></sa-empty>
          </template>
          <el-table-column type="expand">
            <template #default="props">
              <el-table class="sa-table sa-expand-table" :data="skuPrice.data" stripe>
                <el-table-column width="96"></el-table-column>
                <el-table-column prop="id" label="ID" min-width="80"></el-table-column>

                <el-table-column label="商品" min-width="440">
                  <template #default="scope">
                    <div class="sa-flex sa-m-l-16">
                      <sa-preview :url="scope.row.image || props.row.image" size="32"></sa-preview>
                      <div class="sku-text sa-m-l-28">
                        {{ scope.row.goods_sku_text?.join('/') }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="price"
                    label="价格"
                    min-width="150"
                    align="center"
                ></el-table-column>
                <el-table-column
                    prop="sales"
                    label="销量"
                    min-width="100"
                    align="center"
                ></el-table-column>
                <el-table-column label="浏览量" min-width="100" align="center">
                  <template #default="scope">{{ scope.row.views || '-' }}</template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" min-width="100" align="center"/>
                <el-table-column label="更新时间" width="172">
                  <template #default>-</template>
                </el-table-column>
                <el-table-column label="操作" min-width="240">
                  <template #default="scope">
                    <el-button v-auth="'shop.admin.goods.skuprice.edit'" link>
                      <el-dropdown popper-class="goods-dropdown" @command="handleSkuCommand">
                        <el-tag :type="statusList.color[scope.row.status]">
                          <span>{{ scope.row.status_text }}</span>
                          <el-icon class="sa-m-l-4">
                            <ArrowDown/>
                          </el-icon>
                        </el-tag>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item
                                :command="{
                                goodsId: props.row.id,
                                id: scope.row.id,
                                type: 'up',
                              }"
                            >
                              <span class="status-up">上架</span>
                            </el-dropdown-item>
                            <el-dropdown-item
                                :command="{
                                goodsId: props.row.id,
                                id: scope.row.id,
                                type: 'down',
                              }"
                            >
                              <span class="status-down">下架</span>
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column type="selection" width="48" align="center"></el-table-column>
          <el-table-column sortable="custom" prop="id" label="ID" min-width="80"></el-table-column>
          <el-table-column label="商品" min-width="440">
            <template #default="scope">
              <goods-item
                  :goods="{
                  image: scope.row.image,
                  title: scope.row.title,
                  subtitle: scope.row.subtitle,
                  activities: scope.row.activities,
                  promos: scope.row.promos,
                }"
                  mode="goods"
              ></goods-item>
            </template>
          </el-table-column>
          <el-table-column prop="type_text" label="商品类型" min-width="150" align="center"></el-table-column>
          <el-table-column label="渠道商" min-width="150">
            <template #default="scope">{{ scope.row.supplier || '-' }}</template>
          </el-table-column>
          <el-table-column
              sortable="custom"
              prop="price"
              label="价格"
              min-width="150"
              align="center"
          >
            <template #default="scope">
              <div>{{ scope.row.price?.join('~') || 0 }}</div>

              <div class="sku" v-if="scope.row.is_sku" @click.stop="expandRow(scope.row.id)">
                <span>多规格</span>
                <el-icon
                    :class="[
                    'expand-arrow sa-m-l-4',
                    expandRowKeys.includes(scope.row.id) ? 'expand-arrow-up' : 'expand-arrow-down',
                  ]"
                >
                  <ArrowDown/>
                </el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column
              sortable="custom"
              prop="sales"
              label="销量"
              min-width="100"
              align="center"
          ></el-table-column>
          <el-table-column
              sortable="custom"
              prop="views"
              label="浏览量"
              min-width="100"
              align="center"
          ></el-table-column>
          <el-table-column label="库存" min-width="100" align="center">
            <template #default="scope">
              <div class="sa-flex sa-row-center stock">
                <span>{{ scope.row.stock || 0 }}</span>
                <el-button v-auth="'shop.admin.goods.goods.addstock'" class="add-stock" link>
                  <sa-icon name="sa-shop-goods-add-stock" @click="editStock(scope.row)"/>
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" width="172">
            <template #default="scope">{{ scope.row.create_time || '-' }}</template>
          </el-table-column>
          <el-table-column label="操作" min-width="240" fixed="right">
            <template #default="scope">
              <div class="sa-flex">
                <el-button v-auth="'shop.admin.goods.goods.edit'" link>
                  <el-dropdown popper-class="goods-dropdown" @command="handleCommand">
                    <el-tag :type="statusList.color[scope.row.status]">
                      <span>{{ scope.row.status_text }}</span>
                      <el-icon class="sa-m-l-4">
                        <ArrowDown/>
                      </el-icon>
                    </el-tag>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                            :command="{
                            id: scope.row.id,
                            type: 'up',
                          }"
                        >
                          <span class="status-up">上架</span>
                        </el-dropdown-item>
                        <el-dropdown-item
                            :command="{
                            id: scope.row.id,
                            type: 'down',
                          }"
                        >
                          <span class="status-down">下架</span>
                        </el-dropdown-item>
                        <el-dropdown-item
                            :command="{
                            id: scope.row.id,
                            type: 'hidden',
                          }"
                        >
                          <span class="status-hidden">隐藏</span>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-button>
                <el-button
                    v-auth="'shop.admin.goods.goods.detail'"
                    class="is-link sa-m-l-12"
                    type="primary"
                    @click="editRow(scope.row)"
                >编辑
                </el-button
                >
                <el-button
                    v-auth="'shop.admin.goods.goods.add'"
                    class="is-link sa-m-l-12"
                    type="primary"
                    @click="onCopy(scope.row.id)"
                >复制
                </el-button
                >
                <el-popconfirm
                    width="fit-content"
                    confirm-button-text="确认"
                    cancel-button-text="取消"
                    title="确认删除这条记录?"
                    @confirm="deleteRow(scope.row.id)"
                >
                  <template #reference>
                    <el-button
                        v-auth="'shop.admin.goods.goods.delete'"
                        class="is-link"
                        type="danger"
                    >
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <sa-view-bar>
      <template #left>
        <sa-batch-handle
            :batchHandleTools="batchHandleTools"
            :selectedLeng="table.selected.length"
            @batchHandle="batchHandle"
        ></sa-batch-handle>
      </template>
      <template #right>
        <sa-pagination :pageData="pageData" @updateFn="getData"/>
      </template>
    </sa-view-bar>
  </el-container>
</template>
<script>
export default {
  name: 'shop.admin.goods.goods',
};
</script>
<script setup>
import {onMounted, reactive, ref} from 'vue';
import {api} from '../goods.service';
import {api as categoryApi} from '@/app/shop/admin/category/category.service';
import {ElMessageBox} from 'element-plus';
import {useModal, usePagination} from '@/sheep/hooks';
import {useSearch} from '@/sheep/components/sa-table/sa-search/useSearch';
import {composeFilter} from '@/sheep/utils';
import {useRouter} from 'vue-router';
import GoodsItem from '@/app/shop/components/goods-item.vue';
import GoodsEdit from './edit.vue';
import GoodsUpload from './upload.vue';
import GoodsRecyclebin from './recyclebin.vue';
import GoodsStock from './stock.vue';
import SelfSearch from './search.vue';
import {cloneDeep} from 'lodash';

const router = useRouter();
// getType
const statusList = reactive({
  data: [],
  color: {
    all: '',
    up: 'success',
    down: 'danger',
    hidden: 'info',
  },
});

async function getType() {
  const {data} = await api.goods.getType();
  for (var key in filterParams.tools) {
    if (filterParams.tools[key].field == 'activity_type') {
      filterParams.tools[key].options.data = data.activity_type;
    }
  }
  statusList.data = data.status;
}

// getCategory
async function getCategory() {
  const {data} = await categoryApi.select();
  for (var key in filterParams.tools) {
    if (filterParams.tools[key].field == 'category_ids') {
      filterParams.tools[key].options.data = data;
    }
  }
}

const filterParams = reactive({
  tools: {
    status: {label: '商品状态', value: ''},
    keyword: {
      type: 'tinputprepend',
      placeholder: '请输入查询内容',
      field: 'keyword',
      keyword: {
        field: 'id',
        value: '',
      },
      options: [
        {
          label: '商品ID',
          value: 'id',
        },
        {
          label: '商品名称',
          value: 'title',
        },
        {
          label: '商品副标题',
          value: 'subtitle',
        },
        {
          label: '渠道商',
          value: 'supplier',
        },
      ],
    },
    category_ids: {
      type: 'tcascader',
      label: '商品分类',
      field: 'category_ids',
      value: [],
      options: {
        data: [],
        props: {
          children: 'children',
          label: 'name',
          value: 'id',
          checkStrictly: true,
          emitPath: false,
          multiple: true,
        },
      },
    },
    activity_type: {
      type: 'tselect',
      label: '活动类型',
      field: 'activity_type',
      value: '',
      options: {
        data: [],
        props: {
          label: 'name',
          value: 'type',
        },
      },
    },

    sales: {label: '销量区间', value: {min: '', max: ''}},
    price: {label: '价格区间', value: {min: '', max: ''}},
  },
  data: {
    status: 'all',
    keyword: {field: 'id', value: ''},
    category_ids: [],
    activity_type: '',
    price: {min: '', max: ''},
    sales: {min: '', max: ''},
  },
  conditionLabel: {},
});
const {openFilter, deleteFilter} = useSearch({
  comp: SelfSearch,
  filterParams,
  getData,
});

const loading = ref(true);

// 表格
const table = reactive({
  data: [],
  order: 'desc',
  sort: 'id',
  selected: [],
});

const {pageData} = usePagination();

// 获取数据
async function getData(page) {
  loading.value = true;
  if (page) pageData.page = page;
  let tempSearch = cloneDeep(filterParams.data);
  console.log('tempSearch:',tempSearch);
  if (tempSearch.price.min && tempSearch.price.max) {
    tempSearch.price = `${tempSearch.price.min} - ${tempSearch.price.max}`;
  }
  if (tempSearch.sales.min && tempSearch.sales.max) {
    tempSearch.sales = `${tempSearch.sales.min} - ${tempSearch.sales.max}`;
  }
  let search = composeFilter(tempSearch, {
    title: 'like',
    subtitle: 'like',
    category_ids: {
      spacer: ',',
    },
    price: 'between',
    sales: 'between',
  });
  const {error, data} = await api.goods.list({
    page: pageData.page,
    list_rows: pageData.list_rows,
    ...search,
    order: table.order,
    sort: table.sort,
  });
  if (error === 0) {
    table.data = data.data;
    pageData.page = data.current_page;
    pageData.list_rows = data.per_page;
    pageData.total = data.total;
    if (expandRowKeys.length > 0) {
      getSkuPrice(expandRowKeys[0]);
    }
  }
  loading.value = false;
}

// table 字段排序
function fieldFilter({prop, order}) {
  table.order = order == 'ascending' ? 'asc' : 'desc';
  table.sort = prop;
  getData();
}

// table 批量选择
function changeSelection(row) {
  table.selected = row;
}

// 批量操作
const batchHandleTools = [
  {
    type: 'delete',
    label: '删除',
    auth: 'shop.admin.goods.goods.delete',
    class: 'danger',
  },
  {
    type: 'up',
    label: '上架',
    auth: 'shop.admin.goods.goods.edit',
    class: 'success',
  },
  {
    type: 'down',
    label: '下架',
    auth: 'shop.admin.goods.goods.edit',
    class: 'danger',
  },
  {
    type: 'hidden',
    label: '隐藏',
    auth: 'shop.admin.goods.goods.edit',
    class: 'info',
  },
];

async function batchHandle(type) {
  let ids = [];
  table.selected.forEach((row) => {
    ids.push(row.id);
  });
  switch (type) {
    case 'delete':
      ElMessageBox.confirm('此操作将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteRow(ids.join(','));
      });
      break;
    default:
      handleCommand({id: ids.join(','), type: type});
  }
}


function uploadFile() {
  useModal(
      GoodsUpload,
      {
        title: '文件上传',
        type: 'file',
      },
      {
        confirm: () => {
          getData();
        },
      },
  );
}


function addRow() {
  useModal(
      GoodsEdit,
      {
        title: '添加商品',
        type: 'add',
      },
      {
        confirm: () => {
          getData();
        },
      },
  );
}

function editRow(row) {
  useModal(
      GoodsEdit,
      {
        title: '编辑',
        type: 'edit',
        id: row.id,
      },
      {
        confirm: () => {
          getData();
        },
      },
  );
}

function onCopy(id) {
  useModal(
      GoodsEdit,
      {
        title: '复制',
        type: 'copy',
        id,
      },
      {
        confirm: () => {
          getData();
        },
      },
  );
}

async function deleteRow(id) {
  await api.goods.delete(id);
  getData();
}

function openRecyclebin() {
  useModal(
      GoodsRecyclebin,
      {
        title: '回收站',
      },
      {
        confirm: () => {
          getData();
        },
        close: () => {
          getData();
        },
      },
  );
}

let expandRowKeys = reactive([]);

function expandRow(id) {
  skuPrice.data = [];
  if (expandRowKeys.includes(id)) {
    expandRowKeys.length = 0;
  } else {
    expandRowKeys.length = 0;
    expandRowKeys.push(id);
    getSkuPrice(id);
  }
}

const skuPrice = reactive({
  data: [],
});

async function getSkuPrice(id) {
  const {data} = await api.goods.getSkuPrice(id);
  skuPrice.data = data;
}

async function handleCommand(e) {
  await api.goods.edit(e.id, {
    status: e.type,
  });
  getData();
}

async function handleSkuCommand(e) {
  await api.goods.updateSkuPrice(e.id, e.type);
  getSkuPrice(e.goodsId);
}

function jumpAc(data) {
  router.push({
    path: '/shop/admin/activity/list',
    query: {
      type: data.type,
    },
  });
}

function editStock(row) {
  useModal(
      GoodsStock,
      {
        title: '补充库存',
        id: row.id,
        stock: row.stock || 0,
        is_sku: row.is_sku,
      },
      {
        confirm: () => {
          getData();
        },
      },
  );
}

onMounted(() => {
  getCategory();
  getType();
  getData();
});
</script>
<style lang="scss">
.goods-dropdown {
  .status-up {
    color: var(--el-color-success);
  }

  .status-down {
    color: var(--el-color-danger);
  }

  .status-hidden {
    color: var(--el-color-info);
  }
}
</style>
<style lang="scss" scoped>
.el-upload {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  line-height: 1;
  height: 32px;
  white-space: nowrap;
  cursor: pointer;
  color: var(--el-button-text-color);
  text-align: center;
  box-sizing: border-box;
  outline: none;
  transition: 0.1s;
  font-weight: var(--el-button-font-weight);
  user-select: none;
  vertical-align: middle;
  -webkit-appearance: none;
  background-color: var(--el-button-bg-color);
  padding: 8px 15px;
  font-size: var(--el-font-size-base);
  border-radius: var(--el-border-radius-base);
}

.goods-view {
  .el-main {
    .sa-table-wrap {
      margin-left: -48px;
      overflow: hidden;
      height: 100%;

      :deep() {
        .el-table__empty-text {
          margin-left: 48px;
        }
      }

      .title {
        height: 20px;
        line-height: 20px;
        font-size: 14px;
        color: var(--sa-font);
      }

      .subtitle {
        height: 16px;
        line-height: 16px;
        font-size: 12px;
        color: var(--sa-subfont);
      }

      .goods-tag {
        max-width: 76px;
        padding: 3px 8px;
        border-radius: 10px;
        line-height: 14px;
        font-size: 12px;
        font-weight: 400;
        margin-right: 8px;
        cursor: pointer;

        &:last-of-type {
          margin-right: 0;
        }

        &.promos-goods {
          color: #faad14;
          background: rgba(250, 173, 20, 0.16);
        }

        &.groupon_ladder-goods,
        &.groupon-goods {
          color: var(--el-color-primary);
          background: var(--t-bg-active);
        }

        &.seckill-goods {
          color: #ff4d4f;
          background: rgba(255, 77, 79, 0.16);
        }
      }

      .sku {
        width: fit-content;
        height: 20px;
        line-height: 1;
        display: inline-flex;
        align-items: center;
        padding: 0 8px;
        font-size: 12px;
        color: #fff;
        background: var(--el-color-primary);
        border-radius: 10px;
        cursor: pointer;
      }

      .stock {
        cursor: pointer;

        .add-stock {
          margin-left: 8px;
          color: var(--el-color-primary);
        }
      }

      .el-tag {
        padding: 0 8px;
        border: none;
        cursor: pointer;

        :deep() {
          .el-tag__content {
            display: flex;
            align-items: center;
          }
        }
      }
    }

    .sa-expand-table {
      :deep() {
        .el-table__header-wrapper {
          display: none;
        }
      }

      .sku-text {
        font-size: 12px;
        color: var(--sa-font);
      }
    }
  }

  .expand-arrow {
    color: #fff !important;
  }
}
</style>
